<?php
// Copyright 2012 @Wondershare
// $Id: Tfacebook.php 437210 2012-07-26 09:59:56Z xuwh $

require_once(Yii::app()->extensionPath.'/facebook/facebook.php');
class Tfacebook{
    public $facebook;
	public $is_test=false;
	protected $test_call_key='wst_code';
	protected $redirect_uri;
	public function __construct($options=array())
	{
		$this->redirect_uri=$options['redirect_uri'];
		$this->facebook=new facebook($options);
	}
	
	public function get_login_url($redirect)
	{
		$_get = array(
			'redirect' => $redirect, 
			'from' => isset($_GET['from'])?$_GET['from']:'', 
			'id' => isset($_GET['id'])?$_GET['id']:'', 
			'siteid' => isset($_GET['siteid'])?$_GET['siteid']:'', 
			'base_domain' => $_SERVER['HTTP_HOST'], // Facebook 需要这个
		);
		if(empty($_get['redirect']))unset($_get['redirect']);
		$get_str = http_build_query($_get);		

		if($this->is_test){
			$uri=$_SERVER['REQUEST_URI'];
			$path=parse_url($uri,PHP_URL_PATH);
			return $path.'?'.$get_str.'&'.$this->test_call_key.'='.time();
		}
		
		$provider = 'facebook';
		$ret=$this->facebook->getLoginUrl(array(
				'redirect_uri' =>"{$this->redirect_uri}{$get_str}", 
				'scope' => 'email,user_birthday'
		));
		return $ret;
	}
	
	public function is_callback_url()
	{		
		if($this->is_test){
			$flag=(isset($_GET[$this->test_call_key]))?true:false;
			if($flag && !isset($_GET['is_return'])){
echo <<<EOT
<form method="get" >
	<input type="hidden" name="is_return"  />
EOT;
foreach($_GET as $k  => $v){
	echo "{$k}:<input name='".$k."' value='".$v."' type='hiddenx' /><br />";
}
echo <<<EOT
	
	<hr />
	Email<input name="email" value="xx@xx.com" /><br />
	birthday<input name="birthday" value="" /><br />
	<input type="submit" />
</form>
EOT;
				exit;
			}
			return $flag;
		}
		return (isset($_GET['code']))?true:false;
			// torefresh accesstoken;
			//  后面的没有用到
/* 			
			$this->facebook->setAccessToken(null);
			$token=$this->facebook->getAccessToken();
			return $token?true:false; */
		
	}
	public function get_user()
	{
		if($this->is_test){
			$ret=$_GET;
			unset($ret['code']);
			unset($ret['is_return']);
			return $ret;
		}
		//$user=$obj->getUser(); // Only user ID
		$ret=$this->facebook->api('me');
		//debug($ret);
		return $ret;
	
	}
	
	public function set_url($urlArr){
		return;
	}
} 